<template>
  <div>
    <div class="tips" v-if="$store.state.session.user.type === 'agent'">{{$t('monitor.tips2')}}</div>
    <div v-show="!isActive" class="wrap">
      <affix :label="$t('monitor.dataSummary')" :bodyStyle="{paddingTop:'30px'}" >
      <span slot="questionSlot">
        <span class="tip" @click.stop="detail">{{$t('monitor.clickDetail')}}</span>
      </span>
        <el-row :gutter="10">
          <el-col :span="6" class="position-re">
            <square-detail :data="showData[0]" :num="phoneAccountCalls" :tooltip="{width: 310, content: $t('monitor.tooltipCall0')}" :computedNum="inCallAgentCount"></square-detail>
          </el-col>
          <el-col :span="6" class="position-re">
            <square-detail :data="showData[1]" :num="phoneAccountCalls.inType" :tooltip="{width: 310, content: $t('monitor.tooltipCall1')}"></square-detail>
          </el-col>
          <el-col :span="6" class="position-re">
            <square-detail :data="showData[2]" :num="phoneAccountCalls" :tooltip="{width: 400, content: $t('monitor.tooltipCall2')}"></square-detail>
          </el-col>
          <el-col :span="6" class="position-re">
            <square-detail :data="showData[3]" :num="summary" :tooltip="{width: 260, content: $t('monitor.tooltipCall3')}"></square-detail>
          </el-col>
          <el-col :span="6" class="position-re">
            <square-detail :data="showData[4]" :num="waitCount" :tooltip="{width: 440, content: $t('monitor.tooltipCall4')}"></square-detail>
          </el-col>
          <el-col :span="6" class="position-re">
            <square-detail :data="showData[5]" :num="agentsStatus" :tooltip="{width: 450, content: $t('monitor.tooltipCall5')}"></square-detail>
          </el-col>
          <el-col :span="6" class="position-re">
            <square-detail :data="showData[6]" :num="agentsStatus" :tooltip="{width: 320, content: $t('monitor.tooltipCall6')}"></square-detail>
          </el-col>
          <el-col :span="6" class="position-re">
            <square-detail :data="showData[7]" :num="limitData" :tooltip="{width: 380, content: $t('monitor.tooltipCall7')}"></square-detail>
          </el-col>
        </el-row>
      </affix>
      <affix :label="$t('monitor.callAgentMonitor')" :bodyStyle="{paddingTop:'30px'}">
        <el-form ref="form" :model="form" label-position="left" :inline="true">
          <el-form-item :label="$t('public.agent')">
            <search module="call" power="call" @change="agentSearch" ref="searchAgent"></search>
          </el-form-item>
          <br>
          <el-form-item :label="$t('monitor.busyType')">
            <el-select size="mini" v-model="form.login" collapse-tags @change="search" :placeholder="$t('public.pleasePick')" filterable :multiple="true" class="width-full">
              <el-option
                v-for="(item,index) in loginState"
                :label="item.label"
                :key="index"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('monitor.agentState')">
            <el-select size="mini" v-model="form.state" collapse-tags @change="search" :placeholder="$t('public.pleasePick')" filterable :multiple="true" class="width-full">
              <el-option-group
                v-for="(group, index) in allState"
                :key="index"
                :label="group.label">
                <el-option
                  v-for="(item, index) in group.options"
                  :key="index"
                  :label="item"
                  :value="item">
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('monitor.agentVersion')">
            <el-select size="mini" v-model="form.version" collapse-tags @change="search" :placeholder="$t('public.pleasePick')" filterable :multiple="true" class="width-full">
              <el-option
                v-for="(item, index) in allVersion"
                :key="index"
                :label="item.code_name"
                :value="item.code_value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="clearBoth config">
          <div class="fr">
            <el-button class="" size="small" @click="configStateTime" v-if="showTimeoutTotificatioBtn">{{$t('monitor.stateWarningConfig')}}</el-button>
            <el-button class="" size="small" @click="config" v-if="configHeaderShow">{{$t('monitor.setHeaderConfig')}}</el-button>
          </div>
        </div>
        <!--坐席详情组件-->
        <table-agent
          :allList="searchAgent"
          class="monitor-table"
          :cacheAgent="this.cacheAgent"
          :header="monitorHeader"></table-agent>
      </affix>
      <!--表头配置组件-->
      <header-option :show="isShow" :option="headOptionsShow"  :noDrag="headOptionsNoShow" type="monitor_agent_call" v-on:close="close"></header-option>
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('monitor.stateWarningConfig')" :visible.sync="dialogObj.show">
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            {{dialogObj.form}}
            <el-form label-position="left" ref="form" :model="dialogObj.form">
              <el-form-item :label="dialogObj.data[key]" v-for="(item, key) in dialogObj.form" :key="key">
                <el-input size="mini" v-model.trim="dialogObj.form[key]">
                  <template slot="append">{{$t('public.minutes2')}}</template>
                </el-input>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="12" class="tips">
            <h6 v-once>{{$t('monitor.monitorNotifyH6')}}</h6>
            <p v-once>
              {{$t('monitor.monitorNotifyContent')}}
            </p>
          </el-col>
        </el-row> -->
        <Timeoutnotification ref='timeoutTification' :data='dialogObj' :isShow='dialogObj.show' ></Timeoutnotification>
        <span slot="footer" class="dialog-footer">
        <el-button type="primary" class="primary_btn" @click="saveStateTime">{{$t('public.save')}}</el-button>
      </span>
      </el-dialog>
    </div>
    <keep-alive>
      <component :is="isActive" @back="back"></component>
    </keep-alive>
  </div>
</template>
<script>
  import Affix from '../../ui-modules/affix/Affix'
  import squareDetail from './base/squareDetail'
  import headerOption from '../report/base/headerOption.vue'
  import search from './base/AgentSearch'
  import callData from './callDataCompare'
  import tableAgent from './base/tableAgent'
  import {checkform} from '@/utils/validate'
  import bus from '@/store/eventBus'
  import {isHasMenu} from '@/utils/m7Utils'
  import Timeoutnotification from '../monitor.old/Timeoutnotification.vue'
  export default {
    name: 'callMonitor',
    data () {
      return {
        form: {
          login: [], // 登录状态
          state: [], // 坐席状态
          version: [] //座席版本
        },
        cacheAgent: [], // 坐席组件筛选出的坐席
        loginState: [
          {label: this.$t('login.loginBtn'), value: 'on'},
          {label: this.$t('monitor.logout'), value: 'off'}
        ],
        showData: [
          {
            main: {value: 'inCalls', name: this.$t('monitor.todayInSum')},
            sub: [{value: 'inComplete', name: this.$t('monitor.comingSum')},
              {value: 'inComplete', type: 'rate', name: this.$t('monitor.comingSumRate')},
              {value: 'inComplete', type: 'rateOther', name: this.$t('workbench.completingAgentRate')}
            ]
          },
          {
            main: {value: 'InNotDeal', name: this.$t('monitor.InNotDeal'), type: 'red'},
            sub: []
          },
          {
            main: {value: 'outCalls', name: this.$t('monitor.outCallSumToday')},
            sub: [{value: 'outComplete', name: this.$t('monitor.outSum')}, {value: 'outComplete', type: 'rate', name: this.$t('monitor.outSumRate')}]
          },
          {
            main: {value: 'dailinTime', name: this.$t('monitor.dailinTime'), type: 'time'},
            sub: [{value: 'dailoutTime', name: this.$t('monitor.dailoutTime'), type: 'time'}]
          },
          {
            main: {value: 'waitCountTotal', name: this.$t('monitor.waitCountTotal'), type: 'red'},
            sub: [{value: 'inQueueLeak', name: this.$t('monitor.inQueueLeak')}]
          },
          {
            main: {value: 'calling', name: this.$t('monitor.calling')},
            sub: [{value: 'busy', name: this.$t('monitor.busyState')}, {value: 'rest', name: this.$t('monitor.restState')}, {value: 'other', name: this.$t('monitor.otherState')}]
          },
          {
            main: {value: 'free', name: this.$t('monitor.idleAgent')},
            sub: [{value: 'online', name: this.$t('monitor.onlineAgent')}, {value: 'offline', name: this.$t('monitor.offlineAgent')}, {value: 'licece', name: this.$t('monitor.licece')}]
          },
          {
            main: {value: 'incomingData', name: this.$t('monitor.incomingData')},
            sub: [{value: 'limit', name: this.$t('monitor.limitUp')}, {value: 'inlimit', name: this.$t('monitor.inlimit'), type: 'red'}]
          }
        ],
        // _cti_ui_desc: {
        //   unregister: '未连接',
        //   peerstate: '空闲',
        //   dialing: '呼叫中',
        //   innerDialing: '呼叫中',
        //   belling: '来电振铃',
        //   innerBelling: '来电振铃',
        //   listening: '监听振铃1',
        //   talking: '普通通话',
        //   threeWayTalking: '三方通话1',
        //   innerTalking: '内部通话',
        //   dialTalking: '外呼通话',
        //   listened: '监听中',
        //   hold: '保持1',
        //   consultTalking: '普通通话',
        //   dialTransfer: '外呼转接通话',
        //   transfer: '转接通话',
        //   offline: '离线接听',
        //   ready: '签出',
        //   transferBelling: '转接振铃1',
        //   transferDialing: '转接振铃'
        // },
        allState: [
          {label: '', options: [this.$t('cti.unlink')], key: 'on'},
          {label: this.$t('monitor.calling'), options: [this.$t('cti.talking'), this.$t('cti.innerTalking'), this.$t('cti.dialTalking'), this.$t('cti.listened'), this.$t('cti.dialTransfer'), this.$t('cti.transferCall')], key: 'on'},
          {label: this.$t('monitor.ring1'), options: [this.$t('cti.dialing'), this.$t('cti.belling')], key: 'on'},
          {label: this.$t('monitor.offline'), options: [this.$t('cti.ready'), this.$t('cti.offline')], key: 'off'}
        ],
        // 登出状态，筛选时使用
        offLIneStateArr: [this.$t('cti.ready'), this.$t('cti.offline')],
        isActive: '',
        headOptionsShow: {},
        scope: 'noScope',
        isShow: false,
        monitorHeader: [],
        headOptionsNoShow: [{'name': 'agentName', displayname: this.$t('public.agent'), 'order': 1, 'show': true}, {'name': 'agentNo', displayname: this.$t('public.jobNumber'), 'order': 2, 'show': true}, {'name': 'answerStyle', displayname: this.$t('monitor.answerMode'), 'order': 3, 'show': true}, {'name': 'version', displayname: this.$t('monitor.agentVersion'), 'order': 4, 'show': true},{'name': 'state', displayname: this.$t('public.state'), 'order': 5, 'show': true}],
        sortObj: {
          name: '',
          type: '',
          num: 0
        },
        dialogObj: {
          show: false,
          data: {},
          callStateData: {},
          form: {}
        },
        showTimeoutTotificatioBtn: true
      }
    },
    props: {
    },
    components: {
      Affix,
      squareDetail,
      search,
      callData,
      tableAgent,
      headerOption,
      Timeoutnotification
    },
    computed: {
      // 总通话数据
      phoneAccountCalls () {
        let pbx = this.$store.state.session.user.pbx
        let data = this.$store.state.cti.globalLet.phone_accountCalls
        return data[pbx] || {}
      },
      // 流转到坐席的呼入数
      inCallAgentCount () {
        let accountCalls = this.phoneAccountCalls
        let inType = accountCalls.inType || {}
        return accountCalls.inComplete + inType.InNotDeal
      },
      // 排队数，排队放弃数
      waitCount () {
        let waitCountTotal = this.summary.waitCountTotal
        let inQueueLeak = 0
        if (this.phoneAccountCalls.inType) {
          inQueueLeak = this.phoneAccountCalls.inType.InQueueLeak
        }
        return {waitCountTotal, inQueueLeak}
      },
      // 坐席各状态数量
      agentsStatus () {
        let agents = this.summary.agents || {}
        if (agents['0']) {
          let calling = agents.calling.value
          let free = agents['0'].value
          let busy = agents['1'].value
          let rest = agents['2'].value
          let unregister = agents['unregister'].value
          let other = unregister || 0
          let online = 0
          let offline = agents.offline.value
          for (let i in agents) {
            if (i > 2) {
              other += agents[i].value
            }
          }
          online = other + free + busy + rest + calling
          let licece = this.summary.allLicece - online - offline
          return {calling, free, busy, rest, other, online, licece, offline}
        } else {
          return {}
        }
      },
      limitData () {
        let limit = this.$store.state.cti.globalLet.limits
        let incomingData = this.summary.incomingData
        let inlimit = 0
        if (this.phoneAccountCalls.inType) {
          inlimit = this.phoneAccountCalls.inType.InLimit
        }
        return {limit, inlimit, incomingData}
      },
      // 显示的坐席数组
      searchAgent () {
        let cacheAgent = this.cacheAgent
        let arr = []
        cacheAgent.forEach(item => {
          if (item.show) {
            arr.push(item._id)
          }
        })
        return arr
      },
      allVersion () {
        return this.$getCache('licenceType')
      }
    },
    inject: ['phonePeers', 'init', 'summary', 'configHeaderShow'],
    watch: {
    },
    methods: {
      back () {
        this.isActive = ''
        bus.$emit('monitor:callMonitorRefresh')
      },
      // 添加电话条状态
      initStateArr (flag) {
        let busyTypeName = this.$store.state.cti.globalLet.busyTypeName
        // let desc = this.$store.state.cti.globalLet._cti_ui_desc
        let phoneBarStatus = []
        // 初始化座席状态select
        for (let key in busyTypeName) {
          phoneBarStatus.push(busyTypeName[key])
          this.allState[0].options.push(busyTypeName[key])
        }
      },
      detail () {
        this.isActive = 'callData'
      },
      // 坐席变化change事件
      agentSearch ({type, leaf, includeSubordinate}) {
        this.cacheAgent = leaf.map(item => {
          return {_id: item, show: true}
        })
        if (includeSubordinate) {
          // 我和我的下属
          let agentList = this.$refs.searchAgent.allAgent
          let getAgent = function (pid) {
            for (var i = 0; i < agentList.length; i++) {
              var obj = agentList[i]
              if (obj.parentId &&
                obj.parentId === pid) {
                if (!this.cacheAgent.some(item => item._id === obj._id)) {
                  this.cacheAgent.push({_id: obj._id, show: true})
                }
                getAgent.call(this, obj._id)
              }
            }
          }
          this.cacheAgent.map((item) => {
            getAgent.call(this, item._id)
          })
        }
        this.search()
      },
      search () {
        this.cacheAgent.forEach((item) => {
          item.show = this.filterCondition(item._id)
        })
      },
      // 搜索条件
      filterCondition (id) {
        // 在线或离线
        let filter1 = true
        // 状态条件
        let filter2 = true
        // 座席版本条件
        let filter3 = true

        let loginState = this.form.login
        let current = this.phonePeers[id] || {}
        let content = current.state ? current.state.content : ''
        if (loginState.length === 1) {
          // 筛选出在线或离线
          let key = loginState[0]
          if (key === 'on' && this.offLIneStateArr.indexOf(content) !== -1) {
            filter1 =  false
          } else if (key === 'off' && this.offLIneStateArr.indexOf(content) === -1) {
            filter1 = false
          } else {
            filter1 = true
          }
        }
        let versionState = this.form.version
        let versionType = current.version
        if (!this.form.state.length) {
          filter2 = true
        } else if (this.form.state.indexOf(content) !== -1) {
          filter2 = true
        } else {
          filter2 = false
        }
        if (versionState.length > 0) {
          filter3 = versionState.indexOf(versionType) > -1
        } else {
          filter3 = true
        }
        return filter1 && filter2 && filter3
      },
      // 状态超时提醒展示
      configStateTime () {
        this.dialogObj.form = {}
        let p1 = this.$store.dispatch('getCache', {type: 'phoneBars'})
        let p2 = this.$store.dispatch('queryAccountMoniterBusyNotice', {pbx: this.$store.state.session.user.pbx})
        Promise.all([p1, p2]).then(([res1, res2]) => {
          this.dialogObj.show = true
          if (res2.MoniterBusyNotice && Object.keys(res2.MoniterBusyNotice).length) {
            res1.forEach((item) => {
              if (item.PhoneBarItemId !== '0' && item.PhoneBarItemId !== '99' && item.IsEnable === '1') {
                let key = 'PhoneBarState' + item.PhoneBarItemId
                this.$set(this.dialogObj.form, key, res2.MoniterBusyNotice[key] || 0)
                this.dialogObj.data[key] = item.PhoneBarItemName
              }
            })
          } else {
            res1.forEach((item) => {
              if (item.PhoneBarItemId !== '0' && item.PhoneBarItemId !== '99' && item.IsEnable === '1') {
                let key = 'PhoneBarState' + item.PhoneBarItemId
                this.$set(this.dialogObj.form, key, 0)
                this.dialogObj.data[key] = item.PhoneBarItemName
              }
            })
          }
          if (res2.CallStatusConfig) {
            this.$set(this.dialogObj, 'callStateData', res2.CallStatusConfig)
          }
        })
      },
      // 保存状态超时提醒
      saveStateTime () {
        // for (let one in this.dialogObj.form) {
        //   if (!this.dialogObj.form[one]) {
        //     this.dialogObj.form[one] = 0
        //   }
        //   let value = this.dialogObj.form[one]
        //   let match = checkform(value, 'Number3')
        //   if (match || value > 1440) {
        //     this.$message.error(this.$t('validate.number3'))
        //     return
        //   } else {
        //     this.dialogObj.form[one] = Number(this.dialogObj.form[one])
        //   }
        // }
        for (let one in this.dialogObj.form) {
          this.dialogObj.form[one] = 0
        }
        this.$refs.timeoutTification.selectdArr.forEach((item)=>{
          this.dialogObj.form[item.key] = item.value
        })
        let RingNotDeal = { "EventType":"RingNotDeal", Times: 0, TimeLength: 0}
        RingNotDeal.OperationType = this.$refs.timeoutTification.conditionValue
        this.$refs.timeoutTification.RingNotDealSelected.forEach((item)=>{
          RingNotDeal[item.key] = item.value
        })
        let callingObj = { "EventType":"Calling",TimeLength: 0}
        this.$refs.timeoutTification.callingSelected.forEach((item)=>{
          callingObj[item.key] = item.value
        })
        this.$store.dispatch('updateAccountMoniterBusyNotice', {pbx: this.$store.state.session.user.pbx, MoniterBusyNotice: this.dialogObj.form, CallStatusConfig: [RingNotDeal, callingObj]}).then((res) => {
          if (res.success) {
            this.dialogObj.show = false
            this.$message.success(this.$t('config.channel.saveSuccess'))
          }
        })
      },
      // 配置表头
      config () {
        this.$store.dispatch('getReportTableHeader', 'monitor_agent_call').then((res) => {
          res.Config.splice(0, 5)
          this.headOptionsShow = res
          this.isShow = !this.isShow
        })
      },
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.$store.dispatch('getReportTableHeader', 'monitor_agent_call').then((res) => {
            res.Config.splice(0, 5)
            this.monitorHeader = res.Config
          })
        }
      },
      // 坐席状态变化,根据搜索条件显示或隐藏该坐席
      agentChangeEvt (peers) {
        peers.forEach((_id) => {
          this.cacheAgent.some((item, index) => {
            if (item._id === _id) {
              this.cacheAgent[index].show = this.filterCondition(item._id)
              return true
            }
          })
        })
      }
    },
    activated () {
      bus.$emit('monitor:callMonitorRefresh')
    },
    beforeMount () {
      // 初始化坐席状态
      this.initStateArr()
      this.init('phonePeersInit')
      // 初始化表头
      this.close('save')
      // 坐席事件
      bus.$on('monitor:agentChange', this.agentChangeEvt)
      let user = this.$store.state.session.user
      if (isHasMenu('func_not_allow_edit_timeout_notification', this.$store.state.session.user) && user.type !== 'admin' && user.exten !== '0000'){
        this.showTimeoutTotificatioBtn = false
      }
    },
    beforeDestroy () {
      bus.$off('monitor:agentChange', this.agentChangeEvt)
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl';
  .wrap
    padding 20px 20px 10px
    .tip
      color $c-main
      cursor pointer
      font-size 12px
      font-weight normal
  .position-re
    position relative
  .tooltip-span
    position absolute
    right 10px
    top 10px
  .icon-tixingweizhi
    border: 1px solid $c-main
    border-radius: 50%
    display: inline-block
    height: 16px
    width: 16px
    text-align: center
    line-height: 16px
    font-size: 10px
    color $c-main
    margin 0 5px
  .config
    padding-bottom 10px
  .padding10
    margin-right  10px
  .tips
    padding 20px 0 0 20px
    color $c-prompt
  .width-full
    width 220px
    margin-right 10px
  .label-name
    display inline-block
    padding-right 20px
    margin-bottom 4px
</style>

